import React from 'react';
import ReactEcharts from '@/components/Echarts';

export function fixNumber(str, len = 1) {
    const result = Number(str).toFixed(len);
    // eslint-disable-next-line no-restricted-globals
    return isNaN(result) ? '' : result;
}

const ProjectPie = ({ data = [] }) => {
    const legendData = data.map(item => item.name);
    // eslint-disable-next-line no-return-assign
    const totalValue = data.reduce((total, item) => (total += item.num), 0);
    const legendArr = data.map(item => [item.num, `${fixNumber((100 * item.num) / totalValue, 2)}%`]);

    const values = legendData.map((item, index) => ({
        name: item,
        value: legendArr[index][0]
    }));

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c}人 ({d}%)'
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            itemGap: 24,
            right: 0,
            top: 25,
            formatter(name) {
                let index = 0;
                legendData.forEach((value, i) => {
                    if (value === name) {
                        index = i;
                    }
                });
                return `${name}  |  ${legendArr[index][1]}     ${legendArr[index][0]}`;
            },
            data: legendData,
            textStyle: {
                color: 'rgba(0,0,0,0.65)',
                fontWeight: 400,
                fontSize: 13
            }
        },
        series: [
            {
                type: 'pie',
                radius: ['45%', '65%'],
                center: ['38%', '50%'],
                label: {
                    show: false,
                    position: 'center'
                },
                labelLine: {
                    show: false
                },
                data: values
            }
        ]
    };

    return (
        <div style={{ position: 'relative' }}>
            <div
                style={{
                    position: 'absolute',
                    textAlign: 'center',
                    color: 'rgba(51,51,51,0.35)',
                    left: 140,
                    top: 108,
                    width: 145,
                    zIndex: 100
                }}
            >
                <div style={{ fontWeight: 600, color: 'rgba(51, 51, 51, 0.85)', fontSize: 24 }}>
                    {totalValue}
                    <span style={{ fontWeight: 500, fontSize: 10 }}>人</span>
                </div>
                <div style={{ fontWeight: 400, fontSize: 12 }}>项目参与人</div>
            </div>

            <ReactEcharts style={{ height: 270 }} option={option} />
        </div>
    );
};

export default ProjectPie;
